<template>
  <el-row v-loading="initLoading">
    <el-col :span="24">
      <el-form class="el-form-col" :model="model" label-position="left" ref="elForm" label-width="100px">
        <Portlet title="订单信息">
          <el-row :gutter="15">

            <el-col :md="12" :lg="8" :xl="6" v-if="orderNo">
              <el-form-item label="出库单号">
                <span>{{ orderNo }}</span>
              </el-form-item>
            </el-col>

            <el-col :md="12" :lg="8" :xl="6">
              <el-form-item label="出库仓" prop="warehouseId" :rules="[
                    {required: true, message: '出库仓必须', trigger: 'change'}
                  ]">
                <el-select v-model="model.warehouseId" placeholder="请选择出库仓">
                  <el-option v-for="item in warehouseIdArr" :key="item.value" :label="item.text"
                             :value="item.value"></el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :md="12" :lg="8" :xl="6">
              <el-form-item label="商家名称" prop="cargoOwnerId" :rules="[
                    {required: true, message: '商家必须', trigger: 'change'}
                  ]">

                <RemoteSelect
                  v-model="model.cargoOwnerId"
                  :config="{
                    text: 'cargoOwnerName',
                    value: 'cargoOwnerId',
                    searchKey: 'cargoOwnerName',
                    url: '/ms-warehouse-order/WhPackage/findCargoOwner'
                  }"
                  :getParams="getParams"
                  :remote="false"
                  :beforeRequest="beforeRequest"
                  ref="cargoOwnerIdSelect"
                  @setOptions="setCargoOwnerOptions"
                  :initOptions="cargoOwnerArr"
                >
                </RemoteSelect>
              </el-form-item>
            </el-col>

            <el-col :md="12" :lg="8" :xl="6">
              <el-form-item label="出库类型" prop="inputTypeCode">
                <span>{{ model.storageTypeCode | filterDataBaseDictionary}}</span>
              </el-form-item>
            </el-col>

          </el-row>
        </Portlet>

        <Portlet title="商品信息">

          <PackageSelectModal out :value="model.productDetailBeans" @addPackage="addPackage"
                              :visible.sync="outerVisible" :cargoOwnerId="model.cargoOwnerId"></PackageSelectModal>
          <el-button slot="tools" type="primary" @click.prevent="showPackageSelectModal">添加</el-button>
          <el-form-item label-width="0" prop="productDetailBeans" :rules="[
                {required: true, message: '货物信息必须', trigger: 'change', type: 'array'}
             ]">
            <PackageTable out v-model="model.productDetailBeans"></PackageTable>
          </el-form-item>

          <el-row :gutter="15">
            <el-col :sm="12" :md="6" :xl="6">
              <el-form-item label="总包件">
                <span>{{ computedTotalPackage }}</span>
              </el-form-item>
            </el-col>

            <el-col :md="12" :lg="8" :xl="6">
              <el-form-item label="建议体积">
                <span>{{ computedTotalVolume | decimalNumFilter }}m³</span>
              </el-form-item>
            </el-col>

            <el-col :sm="12" :md="6" :xl="6">
              <el-form-item
                prop="totalVolume"
                :rules="[
                  {required: true, message: '总体积必须', trigger: 'blur'},
                  {validator: isFormatNumber, int: 9,  message: '总体积必须是整数小于9位小数小于2位的小数', trigger: 'blur'},
                  {validator: range, min: 0.01,  message: '总体积必须大于0', trigger: 'blur'}
                ]"
                label="总体积">
                <el-input :maxlength="50" v-model="model.totalVolume">
                  <template slot="append">
                    <el-button @click.prevent="suggestAllVolume">使用建议</el-button>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>

            <el-col :sm="12" :md="6" :xl="6">
              <el-form-item
                prop="totalWeight"
                :rules="[
                  {validator: isFormatNumber, int: 9,  message: '总重量必须是整数小于9位小数小于2位的小数', trigger: 'blur'},
                  {validator: range, min: 0.01,  message: '总重量必须大于0', trigger: 'blur'}
                ]"
                label="总重量">
                <el-input :maxlength="50" v-model="model.totalWeight">
                  <template slot="append">kg</template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </Portlet>

        <Portlet>
          <el-row>
            <el-col class="text-center" :span="24">
              <el-button :loading="loading" class="btn-block" @click.prevent="submit" type="primary">立即下单</el-button>
              <el-button v-if="isTempOutShow" :loading="loading" class="btn-block" @click.prevent="save" type="primary">
                保存
              </el-button>
            </el-col>
          </el-row>
        </Portlet>
      </el-form>
    </el-col>
  </el-row>
</template>
<script>
import PackageSelectModal from '@/views/oms/order/PackageSelectModal'
import PackageTable from '@/views/oms/order/PackageTable'
import {getMyWarehouse, getAllServiceTypeByType} from '@/utils/selectOptions'
import {copy, dotData, alert, confirm} from '@/utils'
import {filterDataBaseDictionary, decimalNumFilter} from '@/filters'
import {isFormatNumber, isPhone, range} from '@/utils/validate'
import L from 'lodash'

export default {
  components: {
    PackageSelectModal,
    PackageTable
  },
  filters: {
    filterDataBaseDictionary
  },
  data() {
    return {
      id: this.$route.params.id,
      routeName: this.$route.name,
      outerVisible: false,
      loading: false,
      model: {
        productDetailBeans: [],
        storageTypeCode: 'CARGOSOURCETYPE01',
        warehouseId: '',
        cargoOwnerId: '',
        totalVolume: '',
        totalWeight: '',
        orderState: '' // 0:暂存, 1:直接录入
      },
      warehouseIdArr: [],
      cargoOwnerArr: [],
      cargoOwnerLoading: false,
      orderNo: '',
      serviceTypeArr: [],
      initLoading: false,
      orderTempId: '' // 暂存单id
    }
  },
  computed: {
    // 商家名称需要收货仓编号
    cargoOwnerIdNeedWarehouseId() {
      return ['CARGOSOURCETYPE01'].indexOf(this.model.storageTypeCode) >= 0
    },
    // 总包件数
    computedTotalPackage() {
      return this.model.productDetailBeans.reduce((total, item) => {
        const num = parseInt(item.num)
        if (num) {
          return total + num
        }
        return total
      }, 0)
    },
    // 总体积
    computedTotalVolume() {
      return this.model.productDetailBeans.reduce((total, item) => {
        const totalVolume = parseInt(item.num) * parseFloat(item.volume)
        if (totalVolume) {
          return total + totalVolume
        }
        return total
      }, 0)
    },
    isTempOutShow() { // 出库暂存单
      return this.routeName === 'orderTempOutShow'
    }
  },
  watch: {
    // 根据出库类型来
    'model.storageTypeCode'(val, oldVal) {
      if (val === oldVal) {
        return
      }
      if (this.initLoading) {
        return
      }
      this.model.warehouseId = ''
      getMyWarehouse(val).then(arr => {
        this.warehouseIdArr = arr
      })
    },
    warehouseIdArr(val, oldVal) {
      // 只有一个时默认选中
      if (Array.isArray(val) && val.length === 1) {
        this.model.warehouseId = val[0].value
      }
    },
    'model.warehouseId'(val, oldVal) {
      if (val === oldVal) {
        return
      }
      if (this.initLoading) {
        return
      }
      this.model.cargoOwnerId = ''
      if (this.$refs.cargoOwnerIdSelect) {
        this.$refs.cargoOwnerIdSelect.clearOptions()
      }
    }
  },
  created() {
    getMyWarehouse(this.model.storageTypeCode).then(arr => {
      this.warehouseIdArr = arr
    })
    getAllServiceTypeByType('put').then(arr => {
      if (Array.isArray(arr)) {
        this.serviceTypeArr = arr
      }
    })
    // 获取详情数据
    this.httpGetDetail()
  },
  methods: {
    isFormatNumber,
    isPhone,
    range,
    beforeRequest() {
      if (this.cargoOwnerIdNeedWarehouseId && !this.model.warehouseId) {
        alert('请先选择出库仓')
        return false
      }
      return true
    },
    getParams(query) {
      let params = {
        cargoOwnerName: query,
        storageType: this.model.storageTypeCode
      }
      if (this.model.warehouseId) {
        params.warehouseId = this.model.warehouseId
      }
      return params
    },
    remoteMethod: L.debounce((query, _this) => {
      if (!query) {
        _this.cargoOwnerLoading = false
        return
      }
      if (!_this.model.storageTypeCode) {
        alert('请选择出库类型')
        return
      }
      this.$ajax.get('/ms-warehouse-order/WhPackage/findCargoOwner', {
        cargoOwnerName: query,
        storageType: _this.model.storageTypeCode
      }).then(response => {
        const success = dotData(response, 'success')
        if (success) {
          let data = dotData(response, 'data')
          let tempArr = []
          if (Array.isArray(data)) {
            data.forEach((v, k) => {
              tempArr.push({
                text: v.cargoOwnerName,
                value: v.cargoOwnerId
              })
            })
          }
          _this.cargoOwnerArr = tempArr
        }
      }).finally(_ => {
        _this.cargoOwnerLoading = false
      })
    }, 1000),
    remoteQuery() {
      if (!this.model.storageTypeCode) {
        alert('请选择出库类型')
        return
      }
      this.cargoOwnerLoading = true
      // this.remoteMethod(query, this) 改为全部展示
      this.httpGetCargoOwnerAll()
    },
    // 获取所有商家
    httpGetCargoOwnerAll() {
      if (this.cargoOwnerArr.length > 0) {
        this.cargoOwnerLoading = false
        return
      }
      this.$ajax.get('/ms-warehouse-order/WhPackage/findCargoOwner', {storageType: this.model.storageTypeCode}).then(response => {
        const success = dotData(response, 'success')
        if (success) {
          let data = dotData(response, 'data')
          let tempArr = []
          if (Array.isArray(data)) {
            data.forEach((v, k) => {
              tempArr.push({
                text: v.cargoOwnerName,
                value: v.cargoOwnerId
              })
            })
          }
          this.cargoOwnerArr = tempArr
        }
      }).finally(_ => {
        this.cargoOwnerLoading = false
      })
    },
    showPackageSelectModal() {
      if (!this.model.cargoOwnerId) {
        alert('请先选择商家')
        return
      }
      this.outerVisible = true
    },
    httpPost(url) {
      let data = copy(this.model, true)
      // 产品处理
      if (Array.isArray(data.productDetailBeans)) {
        data.packageList = data.productDetailBeans.map(v => {
          return {
            id: v.id,
            packageNum: v.num
          }
        })
        delete data.productDetailBeans
      }
      // 入库暂存单
      if (this.isTempOutShow) {
        data.orderTempId = this.orderTempId
      }
      if (data.totalVolume === '') {
        alert('体积必须')
        return
      }
      return this.$ajax.post(url, data)
    },
    submit() {
      this.$refs.elForm.validate(result => {
        if (!result) {
          alert('验证未通过')
          return
        }
        let url = '/ms-warehouse-order/outWarehose/out-warehouse-place'
        let title = '下单成功'
        this.loading = true
        this.model.orderState = 1
        this.httpPost(url).then(response => {
          const success = dotData(response, 'success')
          if (success) {
            confirm(title, '提示', {
              type: 'success',
              showCancelButton: false,
              closeOnClickModal: false
            }).then(_ => {
              this.afterSubmit()
            }).finally(_ => {
              this.loading = false
            })
          } else {
            this.loading = false
          }
        }).catch(_ => {
          this.loading = false
        })
      })
    },
    save() { // 保存功能
      this.$refs.elForm.validate(result => {
        if (!result) {
          alert('验证未通过')
          return
        }
        const url = '/ms-warehouse-order/outWarehose/out-warehouse-place'
        this.loading = true
        this.model.orderState = 0 // 暂存
        this.httpPost(url).then(response => {
          const success = dotData(response, 'success')
          if (success) {
            confirm('保存成功', '提示', {
              type: 'success',
              showCancelButton: false,
              closeOnClickModal: false
            }).then(_ => {
              this.afterSubmit()
            }).finally(_ => {
              this.loading = false
            })
          } else {
            this.loading = false
          }
        }).catch(_ => {
          this.loading = false
        })
      })
    },
    // 清空表格
    resetFields() {
      try {
        this.$refs.elForm.resetFields()
      } catch (err) {
        console.log(err)
      }
    },
    // 添加包件
    addPackage(arr) {
      let productDetailBeansMap = new Map()
      this.model.productDetailBeans.forEach(v => {
        productDetailBeansMap.set(v.packageId, v)
      })
      arr.forEach(v => {
        if (!productDetailBeansMap.has(v.packageId)) {
          this.$set(v, 'num', '')
          this.model.productDetailBeans.push(v)
        }
      })
    },
    // 设置用户数组
    setCargoOwnerOptions(options) {
      this.cargoOwnerArr = options
    },
    // 建议体积
    suggestAllVolume() {
      if (this.computedTotalVolume) {
        this.model.totalVolume = decimalNumFilter(this.computedTotalVolume)
      } else {
        alert('建议体积要是大于0的数字')
      }
    },
    httpGetDetail() {
      if (this.id) {
        this.initLoading = true
        // 获取订单信息
        let p1 = this.$ajax.get('/ms-warehouse-order/outWarehose/findByOrderInfoTemp', {outOrderId: this.id}).then(response => {
          const success = response.success
          if (success) {
            this.model.warehouseId = dotData(response, 'data.warehouseId')
            this.model.cargoOwnerId = dotData(response, 'data.cargoOwnerId')
            if (this.model.cargoOwnerId) {
              this.cargoOwnerArr = [
                {value: this.model.cargoOwnerId, text: dotData(response, 'data.cargoOwner')}
              ]
            }
            this.orderTempId = dotData(response, 'data.orderId')
            this.model.totalVolume = dotData(response, 'data.totalVolume')
            this.model.totalWeight = dotData(response, 'data.totalWeight')
          }
        })
        // 获取商品信息
        let p2 = this.$ajax.get('/ms-warehouse-order/outWarehose/findByOutWarehouseInfoTemp', {outOrderId: this.id}).then(response => {
          const success = response.success
          if (success) {
            const productDetailBeans = dotData(response, 'data')
            if (Array.isArray(productDetailBeans)) {
              this.model.productDetailBeans = productDetailBeans.map(v => {
                v.num = v.packagePlanNum
                v.id = v.packageId
                v.volume = v.packageOneVolume
                return v
              })
            }
          }
        })

        Promise.all([p1, p2]).finally(_ => {
          this.initLoading = false
        })
      }
    },
    // 在提交之后做的事
    afterSubmit() {
      if (this.isTempOutShow) {
        // 调转列表
        this.$router.push({path: '/redirect/ss-oms/order/temp-out'})
      }
      this.resetFields()
    }
  }
}
</script>
